package net.siufung.mybatis.permit;

import com.baomidou.mybatisplus.extension.plugins.handler.DataPermissionHandler;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author 陈建峰
 * @since 2022/7/25 2:49 下午
 */
@Slf4j
@Component
@AllArgsConstructor
public class MybatisDataPermitHandlerImpl implements DataPermissionHandler {

    private final MybatisDataPermitService mybatisDataPermitService;

    @Override
    public Expression getSqlSegment(Expression where, String mappedStatementId) {
        List<DataPermitModel> dataPermitModelList = mybatisDataPermitService.getDataPermitModelList();
        if(!CollectionUtils.isEmpty(dataPermitModelList)){
            for (DataPermitModel dataPermitModel: dataPermitModelList) {
                if(mappedStatementId.equals(dataPermitModel.getMethod())){
                    return dataScopeFilter(dataPermitModel, where);
                }
            }
        }
        return where;
    }

    private Expression dataScopeFilter(DataPermitModel dataPermitModel, Expression where) {
        try {
            return mybatisDataPermitService.getDataPermitExpression(dataPermitModel, where);
        } catch (JSQLParserException e) {
            e.printStackTrace();
        }
        return where;
    }
}
